/**
 * @program: clms-second
 * @description: mybatisplus的自动填充
 * @author: mitu_echo
 * @create: 2021-07-23 14:10
 **/

package com.second.system.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.second.common.util.JwtUtil;
import com.second.common.util.Payload;
import com.second.system.pojo.entity.User;
import com.second.system.pojo.utils.WebUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class AutoDateConfig implements MetaObjectHandler {

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    private User getUser() {
        // 获取token
        String token = WebUtil.getRequest().getHeader("Token");
        // 解析token
        Payload<User> infoFromToken = JwtUtil.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
        // 获取用户信息
        User userInfo = infoFromToken.getUserInfo();
        return userInfo;
    }
    @Override
    public void insertFill(MetaObject metaObject) {

        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", String.class, LocalDateTime.now().toString());
        // 填充修改时间
        this.strictUpdateFill(metaObject, "updateTime", String.class, LocalDateTime.now().toString());
        // 判断是否是进行登录
        if(!WebUtil.getRequest().getRequestURI().contains("/login")){
            User user = getUser();
            // 填充创建者
            this.strictInsertFill(metaObject, "createBy", String.class, user.getUsername());
            // 填充修改者
            this.strictUpdateFill(metaObject, "updateBy", String.class, user.getUsername());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        // 填充修改时间
        this.strictUpdateFill(metaObject, "updateTime", String.class, LocalDateTime.now().toString());
        // 判断是否是进行登录
        if(!WebUtil.getRequest().getRequestURI().contains("/login")) {
            User user = getUser();
            // 填充修改者
            this.strictUpdateFill(metaObject, "updateBy", String.class, user.getUsername());
        }
    }
}
